﻿//Serializable接口，关于序列化的例子
package javase.io;
import java.io.*; 

//实现Serializable接口，使得MyClass类的对象可以序列化 和 反序列化
class MyClass implements Serializable
{ 
	String s; 
	int i; 
	double d; 
	
	public MyClass(String s,int i,double d)
	{ 
		this.s=s; 
		this.i=i; 
		this.d=d; 
	} 
	
	public String toString()
	{ 
		return "s=" + s + ";i=" + i + ";d=" + d; 
	} 
} 

public class SerializationDemo
{ 
	public static void main(String args[])
	{ 
		//对象序列化 :序列化是把一个对象的状态写入一个字节流的过程
		try
		{ 
			MyClass object1=new MyClass("Hello",-7,2.7e10); 
			System.out.println("object1:"+object1.toString()); 
			
			FileOutputStream fos=new FileOutputStream("serial.txt"); 
			ObjectOutputStream oos=new ObjectOutputStream(fos); 
			oos.writeObject(object1); //往文件中写入对象
			oos.flush();
			oos.close(); 
		} 
		catch(Exception e)
		{ 
			System.out.println("Exception during serialization:"+e); 
			System.exit(0); 
		} 

		//对象反序列化 
		try
		{ 
			MyClass object2; 
			FileInputStream fis=new FileInputStream("serial.txt"); 
			ObjectInputStream ois=new ObjectInputStream(fis); 
			object2=(MyClass)ois.readObject(); //从文件中读取,从字节流返回MyClass对象的状态
			ois.close(); 
			System.out.println("object2:"+object2.toString()); 
		} 
		catch(Exception e)
		{ 
			System.out.println("Exception during deserialization:"+e); 
			System.exit(0); 
		} 
	} 
} 


